/**
 * @license
 * Copyright 2010-2024 Three.js Authors
 * 长方体给定底部4个顶点计算8个点顶点的坐标
 */
import * as THREE from "../threejs/three.module.js";
    // 索引数组，定义每个面由哪些顶点构成 (每个面由两个三角形组成)
    const indicesCube = [
        0, 1, 2, 0, 2, 3,   // 前面
        4, 5, 6, 4, 6, 7,   // 后面
        0, 1, 5, 0, 5, 4,   // 底面
        3, 2, 6, 3, 6, 7,   // 顶面
        0, 3, 7, 0, 7, 4,   // 左面
        1, 2, 6, 1, 6, 5    // 右面
    ];
    const CUBE_TYPES   = ',Z,L,LQ,'  //长方体类别
    const CUBE_TYPE_Z  = 'Z'  //立柱
    const CUBE_TYPE_L  = 'L'  //梁
    const CUBE_TYPE_LQ = 'LQ' //梁墙
// 创建 Raycaster 和鼠标 Vector2
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
export const regHover = (camera, scene, cubes) => {

    const onMouseMove = (event) => {
        // 将鼠标位置归一化到 -1 到 1 之间（适用于 Three.js）
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 投射一条射线
        raycaster.setFromCamera(mouse, camera);

        // 检查与哪些对象相交
        const intersects = raycaster.intersectObjects(scene.children);
       
    }

    // 监听鼠标移动事件
    window.addEventListener('mousemove', onMouseMove, false);
}
export const regClick = (camera, scene, cubes) => {
    // 监听鼠标点击事件
    function onMouseClick(event) {
        // 将鼠标坐标转换为标准化设备坐标 (NDC)
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

        // 通过 Raycaster 检测物体
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObjects(scene.children);
        console.log('intersects=',intersects)
        if (intersects.length > 0) {
            const element = intersects[0]
            const userData = element.object.userData
            if(null==userData || typeof(userData)=='undefined'){
                return
            }
            if(null!=userData.opt && typeof(userData.opt)!='undefined'){
                console.log(userData.opt.name)
            }
           
            if (userData.type) {
                // 显示提示文本并更新位置
                tooltip.style.display = 'block';
                tooltip.style.left = `${event.clientX + 10}px`;  // 将提示框移动到鼠标位置
                tooltip.style.top = `${event.clientY + 10}px`;
                let str = userData.name + '\n';
                const points = userData.points;
                str += JSON.stringify(points).replace(/},/g, '},\n');
                tooltip.textContent = str;  // 显示物体的名字
            } else {
                tooltip.style.display = 'none';
            }

        } else {
            tooltip.style.display = 'none';
        }
    }

    // 监听鼠标点击事件
    window.addEventListener('click', onMouseClick, false);
}

//画长方体
export const drawCubeByPlanes = (hScene,optCubes) => {
    var lstCube = new Array()
    if(hScene==null || typeof(hScene)=='undefined'){
        return lstCube
    }
    if(optCubes==null || typeof(optCubes)=='undefined'){
        return lstCube
    }
    if(!(optCubes instanceof Array)){
        return lstCube
    }
    var iSize = optCubes.length
    var iIdx
    var optCube
    var type,points,indices,opt
    var cube
    for(iIdx=0;iIdx<iSize;iIdx++){
        optCube = optCubes[iIdx];
        if(optCube==null || typeof(optCube)=='undefined' ){
            continue
        }
        type = optCube.type
        points = optCube.points
        indices = optCube.indices
        opt = optCube.opt
        if(indices==null || typeof(indices)=='undefined' ){
            indices = indicesCube
        }
        if(points==null || typeof(points)=='undefined' || !(points instanceof Array)){
            continue
        }
        cube = drawCubeByPlane(hScene,type,points,indices,opt)
        if(null==cube || typeof(cube)=='undefined' ){
            continue
        }
        lstCube.push(cube)
    }
    return lstCube
}

//画长方体
export const drawCubeByPlane = (hScene,type,points,indices,opt) => {
    if(hScene==null ||typeof(hScene)=='undefined'){
        return null
    }
    if(type==null || typeof(type)=='undefined'){
        type = CUBE_TYPE_Z
    }

    var sType = ','+type.toUpperCase()+','
    if(CUBE_TYPES.indexOf(sType)<0){
        type = CUBE_TYPE_Z
    }
    var vertices = pointsToVertices(points,type)
    showVertices(vertices)
    console.log('vertices--',vertices)

    var geometry = new THREE.BufferGeometry();
    geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
    if(indices!=null && typeof(indices)!='undefined'){
        geometry.setIndex(indices);
    }

    var color = 0xdd3c3c
    if(type==CUBE_TYPE_Z){ //立柱
        color = 0xdd3c3c
    }else if(type== CUBE_TYPE_L){ //梁
        color = 0xe1e135
    }else if(type==CUBE_TYPE_LQ){  //梁墙
        color = 0x4d4dff
    }
    geometry.computeVertexNormals(); // 计算法线，确保光照正常
    var material = new THREE.MeshStandardMaterial({
        color: color,
        side: THREE.DoubleSide,
    });
    var cube = new THREE.Mesh(geometry, material);
    cube.castShadow = true;
    cube.userData = {opt:opt,points:points};
    console.log('cube.userData=',cube.userData)
    hScene.add(cube);
    return cube;
}

//长方体给定底部4个顶点计算8个点顶点的坐标
function pointsToVertices(points,type){
    //判别点的合法性
    if(points == null || typeof(points)=='undefined'){
        return null
    }
    var iSize = 0
    if(points instanceof Array){
        iSize = points.length
    }
    if(iSize<4 || iSize>4){
        return null
    }

    console.log('iSize=',iSize,' type=',type)
    var vertices = new Float32Array(24)
    var idx = 0
    var i
    var point
    var x
    var y
    var z
    var z1
    for(i = 0;i<iSize;i++){
        point = points[i]

        console.log('point=',point)
        if(point==null || typeof(point)=='undefined'){
            continue
        }
        x = point.x
        y = point.y
        z = point.z
        
        console.log('XXX i=',i,' x=',x,'y=',y,'z=',z)

        if ((x ==null || typeof(x)=='undefined')  || (y ==null || typeof(y)=='undefined')){
            continue
        }
        if( (z ==null || typeof(z)=='undefined')){
            z = 0
        }
        z1 = z
        if(type=='Z'){
            z1 = z + 330+60
            z  = z + 0
        }else if(type=='L'){
            z1 = z + 330+60
            z  = z + 330
        }else if(type=='LQ'){
            z1 = z + 330+60
            z  = z + 0
        }

        console.log('x=',x,' y=',y,' z=',z,' z1=',z1)
        vertices[idx++ ] = x
        vertices[idx+11] = x
        vertices[idx++ ] = y
        vertices[idx+11] = y
        vertices[idx++ ] = z
        vertices[idx+11] = z1
    }
    return vertices
}

//显示顶点坐标
function showVertices(vertices){
    if(vertices==null ||typeof(vertices)=='undefined'){
        return
    }
    var iSize = 0
    if(vertices instanceof Float32Array){
        iSize = vertices.length
    }
    var idx = 0
    var expr = ''
    var tmp = ''
    console.log('showVertices iSize=',iSize)
    while(idx<iSize){
        expr = ''
        for(var i=0;i<4;i++){
            tmp = ''
            if(idx<iSize){
                if(tmp!=''){
                    tmp += ','
                }
                tmp += vertices[idx++]
            }
            if(idx<iSize){
                if(tmp!=''){
                    tmp += ','
                }
                tmp += vertices[idx++]
            }
            if(idx<iSize){
                if(tmp!=''){
                    tmp += ','
                }
                tmp += vertices[idx++]
            }
            if(tmp!=''){
                if(expr!=''){
                    expr += ','
                }
                expr += '('+tmp + ')'
            }
        }
        if(expr!=''){
            console.log(expr)
        }
    }
}